import * as bm from "/js/baseModule.js";
require(['/js/cropper.min.js']);
require('/js/canvasToBlob.js');
require('/js/binaryAjax.js');
require('/js/exif.js');
require('/js/canvasresize.js');

export class Module extends bm.baseModule {
    constructor(view) {
        super(view);
        let that = this;
        this.tempImg = '';
        this.tempimageurl = '';
        let canvasResize = window['canvasResize'];
        let canvas = document.createElement('canvas');
        this.tempImg = document.createElement("img");
        this.tempImg.style.display = "none";
        $('body').append(this.tempImg);
        this.tempImg.onload = function (event) {
            let img = $(this);
            img.width(img[0].naturalWidth);
            img.height(img[0].naturalHeight);
            if (img.width() > 200) {//按最大高度等比缩放
                let rate = 200 / img.width();
                img.height(img.height() * rate);
                img.width(200);

            }
            let ctx = canvas.getContext("2d");
            if (ctx) {
                ctx.clearRect(0, 0, canvas.width, canvas.height);
                canvas.width = img.width();
                canvas.height = img.height();
                ctx.drawImage(img[0], 0, 0, img.width(), img.height());
                that.tempimageurl = canvas.toDataURL("image/jpeg");
                that.onDataReady(that.tempimageurl);
            }
        };

        $('#init-select, #re-select').change(function () {
            if (this.files && this.files[0]) {
                if ($('#crop').attr('src').length > 0) {
                    that.clear();
                }

                that.showSelect('#init-select', false);
                that.showSelect('#re-select', true);

                // canvasResize（压缩图片）在android上不能用，见demo: http://gokercebeci.com/dev/canvasresize
                // 结果：android上传的头像偏大
                let file = this.files[0];
                if (funs.isAndroid()) {
                    let reader = new FileReader();
                    reader.onload = function (e) {
                        that.tempImg.src = e.target.result;
                    };
                    reader.readAsDataURL(file);
                } else {
                    canvasResize(file, {
                        width: 200,
                        height: 0,
                        crop: false,
                        quality: 100,
                        callback: function (data, width, height) {
                            that.onDataReady(data);
                        }
                    });
                }
            }
        });

        $('#upload').click(function () {
            let canvas = $('#crop').cropper('getCroppedCanvas');
            let base64 = canvas.toDataURL('image/jpeg');
            if (base64) {
                api.uploadAvatar({ img: base64.substr(base64.indexOf(",") + 1) },{
                    succ: function (data) {
                        globalData.user.avatar = data.img;
                        that.clear();
                        that.showSelect('#init-select', true);
                        that.showSelect('#re-select', false);
                        that._evt_goback();
                        funs.getModuleFuns('modules/user/UpdateSupplierInfo.js',function (mod) {
                            mod.setAvatar(data.img);
                        })
                    },
                    fail: function () {
                        funs.tip('上传失败,请重试','','fail',2000);
                    }
                })
            } else {
                funs.tip('抱歉，不支持此浏览器上传图片','','fail',2000);
            }
        })
    }
    afterInstall(){
        let content = this.config.parent.find('.CenterModalContent');
        let height = content.height();
        content.css('margin-top', -height/2+'px');
        setTimeout(function () {
            content.css({'transform':'scale(1,1)','opacity':'1'});
        },100);
    }
    setParams(params) {
        if (params.orgAvatar.length > 0) {
            this.onDataReady(params.orgAvatar);
        }
    }
    onDataReady(data) {
        //ref: https://github.com/fengyuanchen/cropper
        $('#crop').attr('src', data);
        $('#crop').cropper({
            dragMode: 'move',
            aspectRatio: 1,
            autoCropArea: 0.8,
            cropBoxMovable: false,
            cropBoxResizable: false,
            crop: function (e) {
            }
        });
        $('#upload').prop('disabled', false);
    }
    clear() {
        $('#crop').cropper('destroy');
        $('#crop').attr('src', "");
        $('#upload').prop('disabled', true);
    }
    showSelect(jq, b) {
        let label = jq + ' + label';
        if (b) {
            $(jq).removeClass('hide');
            $(label).removeClass('hide');
        } else {
            $(jq).addClass('hide');
            $(label).addClass('hide');
        }
    }

    
}
